package org.vs.handler;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Component;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ClassLoaderHandler {
    private Map<Class, List<Field>> fieldByOrderMap = new HashMap<>();

    public <T> List<T> loader(List<List<Object>> data, Class clazz) throws Exception {
        List<T> res = new ArrayList<>();

        for (List<Object> list : data) {
            List<Object> value = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                value.add(list.get(i));
            }

            T obj = (T) chooseConstructor(clazz.getConstructors(), list)
                    .newInstance(value.toArray());

            res.add(obj);
        }

        return res;
    }

    private Constructor chooseConstructor(Constructor[] constructors, List<Object> data) {
        for (Constructor constructor : constructors) {
            int i = 0;
            for (; i < constructor.getParameterTypes().length; i++) {
                if (!constructor.getParameterTypes()[i].equals(data.get(i).getClass())) {
                    break;
                }
            }

            if (i == constructor.getParameterTypes().length) {
                return constructor;
            }
        }

        return null;
    }
}
